package com.zhixi.config;

import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author zhixi
 */
@Configuration
@EnableCaching
public class CaffeineConfig {

    @Bean
    public CacheManager localEntityCacheManager() {
        CaffeineCacheManager caffeineCacheManager = new CaffeineCacheManager();
        Caffeine<Object, Object> caffeine = Caffeine.newBuilder()
                // 初始大小
                .initialCapacity(10)
                // 最大容量
                .maximumSize(100)
                // 打开统计
                .recordStats()
                // 5分钟不访问自动丢弃
                .expireAfterAccess(5, TimeUnit.MINUTES);
        caffeineCacheManager.setCaffeine(caffeine);
        // 设定缓存器名称
        caffeineCacheManager.setCacheNames(getNames());
        // 值不可为空
        caffeineCacheManager.setAllowNullValues(false);
        return caffeineCacheManager;
    }

    private static List<String> getNames() {
        List<String> names = new ArrayList<>(1);
        names.add("localEntityCache");
        return names;
    }
}